package com.dyh.quickdemozwei.avgDemo1;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;


// 新增游戏状态管理类
class GameState {
    private Map<String, Integer> variables = new HashMap<>();

    public void setVariable(String name, int value) {
        variables.put(name, value);
    }

    public int getVariable(String name) {
        return variables.getOrDefault(name, 0);
    }



    public boolean checkCondition(Condition condition) {
        int actualValue = getVariable(condition.getVariableName());

        switch (condition.getOperator()) {
            case ">":
                return actualValue > condition.getRequiredValue();
            case ">=":
                return actualValue >= condition.getRequiredValue();
            case "<":
                return actualValue < condition.getRequiredValue();
            case "<=":
                return actualValue <= condition.getRequiredValue();
            case "==":
                return actualValue == condition.getRequiredValue();
        }

        return false;
//        return switch (condition.getOperator()) {
//            case ">" -> actualValue > condition.getRequiredValue();
//            case ">=" -> actualValue >= condition.getRequiredValue();
//            case "<" -> actualValue < condition.getRequiredValue();
//            case "<=" -> actualValue <= condition.getRequiredValue();
//            case "==" -> actualValue == condition.getRequiredValue();
//            default -> false;
//        };
    }
}


// 新增条件判断类
class Condition {
    private String variableName;
    private String operator;
    private int requiredValue;

    // Getters
    public String getVariableName() { return variableName; }
    public String getOperator() { return operator; }
    public int getRequiredValue() { return requiredValue; }
}

// 修改后的选项类
class GameOption {
    private String text;
    private String targetParagraphId;
    private List<Condition> conditions; // 新增条件判断
    private Map<String, Integer> effects; // 新增变量影响

    // Getters
    public String getText() { return text; }
    public String getTargetParagraphId() { return targetParagraphId; }
    public List<Condition> getConditions() { return conditions; }
    public Map<String, Integer> getEffects() { return effects; }
}

// 游戏段落结构
class GameParagraph {
    private String id;
    private String text;
    private List<GameOption> options;

    // Getters
    public String getId() { return id; }
    public String getText() { return text; }
    public List<GameOption> getOptions() { return options; }
}

// 剧本解析器
class ScriptParser {
    private static final Gson gson = new Gson();

    public Map<String, GameParagraph> parseScript(Path filePath) throws Exception {
        try (Reader reader = Files.newBufferedReader(filePath)) {
            List<GameParagraph> paragraphs = gson.fromJson(reader, 
                new TypeToken<List<GameParagraph>>(){}.getType());
            
            Map<String, GameParagraph> paragraphMap = new HashMap<>();
            for (GameParagraph paragraph : paragraphs) {
                paragraphMap.put(paragraph.getId(), paragraph);
            }
            return paragraphMap;
        }
    }
}

// 游戏引擎核心
class AVGGameEngine {
    private Map<String, GameParagraph> script;
    private String currentParagraphId;
    private GameState gameState = new GameState();
    private final Scanner scanner = new Scanner(System.in);

    public void loadScript(Path scriptPath) throws Exception {
        ScriptParser parser = new ScriptParser();
        this.script = parser.parseScript(scriptPath);
        this.currentParagraphId = "start"; // 默认起始段落
    }

    public void startGame() {
        while (currentParagraphId != null && !currentParagraphId.equals("end")) {
            GameParagraph current = script.get(currentParagraphId);
            // ... 原有显示逻辑 ...

            // 过滤有效选项
            List<GameOption> validOptions = Optional.ofNullable(current.getOptions())
                    .map(e->e.stream()
                            .filter(option -> checkAllConditions(option.getConditions()))
                            .collect(Collectors.toList())).orElse(null);



            if (validOptions.isEmpty()) {
//                System.out.println("\n【没有可用选项，剧情结束】");
                System.out.println("\n"+ current.getText());
                break;
            }

            // 显示有效选项
            System.out.println("\n请选择：");
            for (int i = 0; i < validOptions.size(); i++) {
                System.out.printf("%d. %s\n", i+1, validOptions.get(i).getText());
            }

            // 处理选择
            int choice = getValidInput(validOptions.size());
            GameOption selected = validOptions.get(choice-1);

            // 应用选项影响
            applyEffects(selected.getEffects());
            currentParagraphId = selected.getTargetParagraphId();
        }
    }

    private boolean checkAllConditions(List<Condition> conditions) {
        if (conditions == null || conditions.isEmpty()) return true;
        return conditions.stream().allMatch(gameState::checkCondition);
    }

    private void applyEffects(Map<String, Integer> effects) {
        if (effects == null) return;
        effects.forEach((varName, delta) -> {
            int current = gameState.getVariable(varName);
            gameState.setVariable(varName, current + delta);
        });
    }

    private int getValidInput(int max) {
        while (true) {
            System.out.print("请输入选择：");
            try {
                int input = Integer.parseInt(scanner.nextLine());
                if (input >= 1 && input <= max) return input;
                System.out.println("输入无效，请重新选择");
            } catch (NumberFormatException e) {
                System.out.println("请输入数字");
            }
        }
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        AVGGameEngine engine = new AVGGameEngine();
        try {
//            engine.loadScript(Path.of("script.json"));
            engine.loadScript(Paths.get("/Users/yuhaodong/work/self/quick-demo-zwei/src/test/java/com/dyh/quickdemozwei/avgDemo1/script1.json"));

            engine.startGame();
        } catch (Exception e) {
            System.err.println("启动失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}